var websock = null;

var global_callback = null;
// var serverPort = '80'; // webSocket连接端口
// var wsuri = 'ws://' + window.location.hostname + ':' + serverPort;
// var wsuri = 'ws://173.16.10.98:9001/business/websocket/qrPayResult';
// console.log(sessionStorage.getItem('session_id'));
// var userId = sessionStorage.getItem('session_id');
// var qrPayResult = Math.round(Math.random() * 1234567890);
// console.log('aaa', window.server.SERVER_API[3].socket);
// var wsuri = window.server.SERVER_API[3].socket + userId;
// var wsuri = window.server.SERVER_API[3].socket + userId;

function createWebSocket(callback) {
    if (websock == null || typeof websock !== WebSocket) {
        initWebSocket(callback);
    }
}

function initWebSocket(callback) {
    global_callback = callback;
    // 初始化websocket

    var userId = sessionStorage.getItem('session_id');
    var wsuri = window.server.SERVER_API[3].socket + userId;
    websock = new WebSocket(wsuri);
    websock.onmessage = function(e) {
        websocketonmessage(e);
    };
    websock.onclose = function(e) {
        websocketclose(e);
    };
    websock.onopen = function() {
        websocketOpen();
    };

    // 连接发生错误的回调方法
    websock.onerror = function() {
        console.log('WebSocket连接发生错误');
        // createWebSocket();啊，发现这样写会创建多个连接，加延时也不行
    };
}

// 实际调用的方法
function sendSock(agentData) {
    if (websock.readyState === websock.OPEN) {
        // 若是ws开启状态
        websocketsend(agentData);
    } else if (websock.readyState === websock.CONNECTING) {
        // 若是 正在开启状态，则等待1s后重新调用
        setTimeout(function() {
            sendSock(agentData);
        }, 1000);
    } else {
        // 若未开启 ，则等待1s后重新调用
        setTimeout(function() {
            sendSock(agentData);
        }, 1000);
    }
}

function closeSock() {
    websock.close();
}

// 数据接收
function websocketonmessage(msg) {
    // console.log("收到数据："+JSON.parse(e.data));
    console.log('收到数据：' + msg);

    global_callback(msg.data);

    // // 收到信息为Blob类型时
    // let result = null;
    // // debugger
    // if (msg.data instanceof Blob) {
    //     const reader = new FileReader();
    //     reader.readAsText(msg.data, 'UTF-8');
    //     reader.onload = (e) => {
    //         result = JSON.parse(reader.result);
    //         console.log('websocket收到--3', result);
    //         (result);
    //     };
    // } else {
    //     // result = JSON.parse(msg.data);
    //     result = msg.data;
    //     console.log('websocket收到--3', result);
    //     global_callback(result);
    // }
}

// 数据发送
function websocketsend(agentData) {
    console.log('发送数据--3：' + agentData);
    websock.send(agentData);
}

// 关闭
function websocketclose(e) {
    console.log('connection closed (' + e.code + ')');
}

function websocketOpen(e) {
    var userId = sessionStorage.getItem('session_id');
    var wsuri = window.server.SERVER_API[3].socket + userId;
    console.log('连接打开', wsuri);
}

export { sendSock, createWebSocket, closeSock };
